import { login, logout } from '@/api/app'


import { setToken, getToken, getUserName, setUserName } from '@/libs/util'

export default {
    state: {
        token: getToken(),
        userName: getUserName(),
    },
    actions: {
        handleLogin({ commit }, { username, password }) {
            username = username.trim()
            return new Promise((resolve, reject) => {
                login({
                    username,
                    password
                }).then(res => {
                    commit('setToken', res.token);
                    commit('setUserName', res.username);
                    resolve()
                }).catch(err => {
                    reject(err)
                })
            })
        },
    },
    mutations: {
        setUserName(state, name) {
            state.userName = name
            setUserName(name)
        },
        setToken(state, token) {
            state.token = token
            setToken(token)
        }
    },
    getters: {
        getUserName(state) {
            return state.userName
        },
        getToken(state) {
            return state.token
        }
    },
}